﻿using System;
using Dotnettools.service;
using MR.AttributeDI;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Dotnettools
{
    [AddToServices(Lifetime.Singleton)]
    public class Rabbitmq : IDisposable
    {


        private LogService _logService;
        private IConnection _connection;
        private IModel _channel;
        public Rabbitmq(LogService logService)
        {
            _logService = logService;
            var factory = new ConnectionFactory
            {
                UserName = ConfigFactory.Instance.config.rabbitmq.user_name,
                Password = ConfigFactory.Instance.config.rabbitmq.password,
                VirtualHost = ConfigFactory.Instance.config.rabbitmq.virtual_host,
                HostName = ConfigFactory.Instance.config.rabbitmq.host_name
            };
            _connection = factory.CreateConnection();
            _channel = _connection.CreateModel();
            _channel.ExchangeDeclare(ConfigFactory.Instance.config.rabbitmq.exchange_name, ExchangeType.Direct, true);
            _channel.QueueDeclare(ConfigFactory.Instance.config.rabbitmq.queue_name, true, false, false, null);
            _channel.QueueBind(ConfigFactory.Instance.config.rabbitmq.queue_name, ConfigFactory.Instance.config.rabbitmq.exchange_name, ConfigFactory.Instance.config.rabbitmq.router_key, null);

        }

        public void sendMsg(string msg)
        {
            _logService.log("send rabbitmq message: " + msg);
            byte[] messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(msg);
            IBasicProperties props = _channel.CreateBasicProperties();
            props.ContentType = "text/plain";
            props.DeliveryMode = 2;
            _channel.BasicPublish(ConfigFactory.Instance.config.rabbitmq.exchange_name,
                ConfigFactory.Instance.config.rabbitmq.router_key, props,
                messageBodyBytes);
        }

        public void startConsumer()
        {
            string consumerTag;
            var consumer = new EventingBasicConsumer(_channel);
            consumer.Received += (ch, ea) =>
            {
                var body = ea.Body;
                string receivedMsg = System.Text.Encoding.UTF8.GetString(body);
                _logService.log("received rabbitmq message: " + receivedMsg);
                _channel.BasicAck(ea.DeliveryTag, false);
            };
            consumerTag = _channel.BasicConsume(ConfigFactory.Instance.config.rabbitmq.queue_name, false, consumer);
        }

        public void Dispose()
        {

        }
    }
}